package com.gugugu.web.rpc.config;


import com.gugugu.web.rpc.server.NettyRpcServerForSpringBoot;
import com.guguguweb.rpc.loadbalancer.imp.RandomLoadBalancer;
import com.guguguweb.rpc.net.client.GuRpcClient;
import com.guguguweb.rpc.net.client.imp.NettyClient;
import com.guguguweb.rpc.net.client.proxy.GuRpcClientProxy;
import com.guguguweb.rpc.serializer.CommonSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AutoGuRpcConfig {

    @Value("${rpc.server.port}")
    private int serverPort;


    @Value("${rpc.client.port}")
    private int clientPort;


    @Value("${rpc.server.NacosPort}")
    private int nacosPort;


    @Value("${rpc.server.serializerCode}")
    private int serializerCode;

    @Value("${rpc.server.NacosHost}")
    private String nacosHost;


    @Bean(name = "defaultGuRpcServer")
    public NettyRpcServerForSpringBoot make(){
        CommonSerializer serializer = CommonSerializer.getByCode(serializerCode);
        if (serializer == null){
            throw new RuntimeException(serializerCode +" 序列化器编号对应的 序列化器不存在");
        }
        return new NettyRpcServerForSpringBoot(nacosHost,nacosPort,serverPort,serializerCode);
    }

    @Bean(name = "defaultGuRpcClient")
    public GuRpcClient makeClient(){
        CommonSerializer serializer = CommonSerializer.getByCode(serializerCode);
        if (serializer == null){
            throw new RuntimeException(serializerCode +" 序列化器编号对应的 序列化器不存在");
        }
        GuRpcClient client = new NettyClient(serializerCode,new RandomLoadBalancer(),
                GuRpcClient.DEFAULT_MAX_WAIT_TIME,nacosHost,nacosPort);
        return client;
    }


    @Bean(name = "defaultGuRpcClientProxy")
    public GuRpcClientProxy makeClientProxy(GuRpcClient defaultGuRpcClient){
        GuRpcClientProxy guRpcClientProxy = new GuRpcClientProxy(defaultGuRpcClient);
        return guRpcClientProxy;
    }
}
